
package com.mego.tzadd.activitys;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.TimePickerView;
import com.mego.tzadd.R;
import com.mego.tzadd.database.dbmodel.Jtdetailinfo;
import com.mego.tzadd.database.manager.JtinfoCenter;
import com.mego.tzadd.utils.HttpRequest;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import zuo.biao.library.base.BaseFragment;
import zuo.biao.library.interfaces.OnHttpResponseListener;
import zuo.biao.library.manager.TimeRefresher;
import zuo.biao.library.ui.AlertDialog;
import zuo.biao.library.util.JSON;


public class JtInfoFragment2 extends BaseFragment implements View.OnClickListener, AlertDialog.OnDialogButtonClickListener, TimeRefresher.OnTimeRefreshListener {
    private final String TAG = "JtInfoFragment2";

    //与Activity通信<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    /**
     * 创建一个Fragment实例
     *
     * @return
     */
    public static JtInfoFragment2 createInstance() {
        return new JtInfoFragment2();
    }

    //与Activity通信>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        setContentView(R.layout.jtinfofragment2);

        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>

        return view;//返回值必须为view
    }

    private EditText edit_ztbs;
    private EditText edit_zchs;
    private TextView tv_xzrq;
    private TextView tv_xzrq1;

    private TextView tv_tblj;
    private TextView tv_chlj;
    private EditText edit_spcb;

    private TimePickerView pvTime;

    int _tblj = 0;
    int _chlj = 0;

    @Override
    public void initView() {//必须在onCreateView方法内调用
        edit_ztbs = (EditText) findViewById(R.id.edit_ztbs);
        edit_zchs = (EditText) findViewById(R.id.edit_zchs);
        tv_xzrq = (TextView) findViewById(R.id.tv_xzrq);
        tv_xzrq1 = (TextView) findViewById(R.id.tv_xzrq1);

        tv_tblj = (TextView) findViewById(R.id.tv_tblj);
        tv_chlj = (TextView) findViewById(R.id.tv_chlj);

        edit_spcb = (EditText) findViewById(R.id.edit_spcb);

        //控制时间范围(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
        //因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(2013, 0, 23);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2029, 11, 28);
        //时间选择器
        pvTime = new TimePickerView.Builder(getContext(), new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                // 这里回调过来的v,就是show()方法里面所添加的 View 参数，如果show的时候没有添加参数，v则为null
                TextView btn = (TextView) v;
                btn.setText(getTimes(date));

//                mHandler.sendEmptyMessage(DOSEARCH);

            }
        })
                //年月日时分秒 的显示与否，不设置则默认全部显示
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("年", "月", "日", "時", "", "")
                .isCenterLabel(true)
                .setSubmitText("確定")
                .setDividerColor(Color.DKGRAY)
                .setContentSize(21)
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setDecorView(null)
                .build();


        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        tv_xzrq.setText(simpleDateFormat.format(date));
        tv_xzrq1.setText(simpleDateFormat.format(date));

        try {
            Thread.sleep(100);
            mHandler.sendEmptyMessage(DOSEARCH);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public static final int DOSEARCH = 1103;

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == DOSEARCH) {
                doQingcu();
            }
        }
    };


    public Jtdetailinfo _jtinfo = null;

    //示例代码>>>>>>>>>
    @Override
    public void initData() {//必须在onCreateView方法内调用
        //示例代码<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        _jtinfo = JtinfoCenter.getInstance().jtdetailinfo;
        //示例代码>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    }
    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initEvent() {//必须在onCreateView方法内调用
        findViewById(R.id.tv_isee).setOnClickListener(this);

        findViewById(R.id.tv_xzrq).setOnClickListener(this);
        findViewById(R.id.tv_xzrq1).setOnClickListener(this);

        findViewById(R.id.tv_guilin0).setOnClickListener(this);
        findViewById(R.id.tv_guilin1).setOnClickListener(this);

        findViewById(R.id.tv_spcb).setOnClickListener(this);

        tv_tblj.setText(_tblj + "");
        tv_chlj.setText(_chlj + "");

        edit_spcb.setText(_jtinfo.getCost() + "");
    }

    String _ztbs = "";
    String _zchs = "";

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.tv_spcb:
                onSpcb();
                break;
            case R.id.tv_isee:
                onIsee();
                break;
            case R.id.tv_xzrq:
                pvTime.show(tv_xzrq);
                break;
            case R.id.tv_xzrq1:
                pvTime.show(tv_xzrq1);
                break;
            case R.id.tv_guilin0:
                if (_isResettblj) {
                    showShortToast("正在投幣累進歸零....");
                    return;
                }
                new AlertDialog(getContext(), "", "確認投幣累進歸零?", "確認", "取消", 15, this).show();
                break;
            case R.id.tv_guilin1:
                if (_isResetchlj) {
                    showShortToast("正在出貨累進歸零....");
                    return;
                }
                new AlertDialog(getContext(), "", "確認出貨累進歸零?", "確認", "取消", 16, this).show();
                break;
        }
    }

    //设置商品成本
    private void onSpcb() {
        new AlertDialog(getContext(), "", "確認设置此機臺商品成本?", true, 19, this).show();

    }

    private void onIsee() {
//        new AlertDialog(getContext(), "", "確認清楚?", "確認", "取消", 13, this).show();
        doQingcu();
    }

    private String getTimes(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    @Override
    public void onDialogButtonClick(int requestCode, boolean isPositive) {
        if (isPositive == false) {
            return;
        }

        if (requestCode == 13) {
            doQingcu();
        } else if (requestCode == 15) {
            doResettblj();
        } else if (requestCode == 16) {
            doResetchlj();
        } else if (requestCode == 19) {
            doSetcost();
        }
    }

    private void doSetcost() {
        showProgressDialog(R.string.loading);
        try {
            int cost  = Integer.parseInt(edit_spcb.getText().toString());
            HttpRequest.jtcost(_jtinfo.getJtid(), cost, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }
                    if (code == 1) {
                        showShortToast("設置成功！");
                    } else {
                        showShortToast("設置失敗！");
                    }
                    dismissProgressDialog();
                }
            });
        } catch (Exception e1) {
            showShortToast("網絡無連接！");
            dismissProgressDialog();
        }
    }

    private void doQingcu() {

        String xzrq = tv_xzrq.getText().toString();
        String xzrq1 = tv_xzrq1.getText().toString();

        showProgressDialog(R.string.loading);
        try {
            HttpRequest.qingchu(_jtinfo.getJtid(), xzrq, xzrq1, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }
                    if (code == 1) {
                        JSONObject a = jsonObject.getJSONObject("data");

                        showShortToast("獲取成功！");
                        edit_ztbs.setText(a.getString("ztbs"));
                        edit_zchs.setText(a.getString("zchs"));
                    } else {
                        showShortToast("獲取失敗！");
                    }
                    dismissProgressDialog();
                }
            });
        } catch (Exception e1) {
            showShortToast("網絡無連接！");
            dismissProgressDialog();
        }
    }

    private void doLjcx() {
        try {
            HttpRequest.ljcx(_jtinfo.getJtid(), 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }
                    if (code == 1) {
                        JSONObject a = jsonObject.getJSONObject("data");

//                        showShortToast("累進獲取成功！");
                        tv_tblj.setText(a.getString("ztbs"));
                        tv_chlj.setText(a.getString("zchs"));
                    } else {
//                        showShortToast("累進獲取失敗！");
                    }
                }
            });
        } catch (Exception e1) {
//            showShortToast("網絡無連接！");
        }
    }

    boolean _isResettblj = false;

    private void doResettblj() {

        if (_isResettblj) {
            return;
        }
        _isResettblj = true;
        showProgressDialog(R.string.loading);
        try {
            HttpRequest.resettblj(_jtinfo.getJtid(), 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }
                    if (code == 1) {
                        JSONObject a = jsonObject.getJSONObject("data");
                        showShortToast("歸零成功！");
                        _tblj = 0;
                        tv_tblj.setText(_tblj + "");
                    } else {
                        showShortToast("歸零失敗！");
                    }
                    _isResettblj = false;
                    dismissProgressDialog();
                }
            });
        } catch (Exception e1) {
            showShortToast("網絡無連接！");
            _isResettblj = false;
            dismissProgressDialog();
        }
    }

    boolean _isResetchlj = false;

    private void doResetchlj() {

        if (_isResetchlj) {
            return;
        }
        _isResetchlj = true;
        showProgressDialog(R.string.loading);
        try {
            HttpRequest.resetchljt(_jtinfo.getJtid(), 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }
                    if (code == 1) {
                        JSONObject a = jsonObject.getJSONObject("data");
                        showShortToast("歸零成功！");
                        _chlj = 0;
                        tv_chlj.setText(_chlj + "");
                    } else {
                        showShortToast("歸零失敗！");
                    }
                    _isResetchlj = false;
                    dismissProgressDialog();
                }
            });
        } catch (Exception e1) {
            showShortToast("網絡無連接！");
            _isResetchlj = false;
            dismissProgressDialog();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //10 秒刷新一次
        TimeRefresher.getInstance().addTimeRefreshListener(TAG, 10000, this);
    }

    @Override
    public void onPause() {
        super.onPause();
        TimeRefresher.getInstance().removeTimeRefreshListener(TAG);
    }

    @Override
    public void onTimerStart() {

    }

    @Override
    public void onTimerRefresh() {
        doLjcx();
    }

    @Override
    public void onTimerStop() {

    }
}